/**
 * 分享海报
 * 2019.04.20
 */
$(function () {
    var _ldgif = $('.cavImgLoading');
    _ldgif.show();
    var mPath = $('#mPath').val(),
        odUrl = _getSessionStorage('oldUrl'),
        shareUrl = mPath+"/admin/shortLink/" + odUrl,
        shareTitle = _getSessionStorage('shareTitle'),
        lookNum =_getSessionStorage('lookNum');
    var type =_getSessionStorage('type');
        if(shareTitle==undefined||shareTitle==''&&type==2){
            shareTitle =  "好友喊你边学边赚积分啦";
        }
    $('.shareTitle').html(shareTitle)
    var promise = new Promise(function (resolve, reject) {
        var qrcodeEle = document.querySelector('#qrcode__wrap');
        var qrcode = new QRCode(qrcodeEle, {
            text: shareUrl,
            width: 128,
            height: 128,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.H
        });
        var vcodeEle = $(qrcodeEle).find('img');
        if(!$("vcodeEle").attr("src")){
            var canvas = $(qrcodeEle).find("canvas")[0];
            var dataURL = canvas.toDataURL("image/png");
            $(vcodeEle).attr("src",dataURL).css("display","block");
        }
        if(vcodeEle !== null || vcodeEle !== 'undefined' || vcodeEle.length >0) {
            resolve(vcodeEle)
        }

        if(type==1){
            $(".integral-txtPic").remove();
            $('.lookNum').html(lookNum);
        }else{
            $(".integral-txtPic").show();
            $(".look").remove();
        }
    });

    promise.then(function (value) {
        bsSwiperFn({
            vcodeImg: value[0],
            _ldgif: _ldgif,
            _type: type
        })
    })
})
//海报交互
var bsSwiperFn = function (params) {
    var bsCurr = $('#bs-current-num'),
        bsTotal = $('#bs-total-num'),
        bsCard = $('.bs-poster-card-center'),
        bsVcode = $('.bs-card-vCode__wrap'),
        mTop = parseInt(bsCard.height()) / 2

    bsCard.css({
        'margin-top': -mTop
    })

    var appendVcode = function (idx, fn) {
        bsVcode.eq(idx).append(params.vcodeImg);
        if($.isFunction(fn)) fn()
    }

    bShareSwiper = new Swiper(".swiper-container-banner", {
        autoplay: false,
        loop: 0,
        centeredSlides: 0,
        slidesPerView: "auto",
        pagination: ".swiper-pagination",
        paginationClickable : true,
        paginationBulletRender: function (swiper, index, className) {
            var imgUrl = '';
            if(swiper !== null && swiper.imagesToLoad !== 'undefined' && swiper.imagesToLoad.length > 0) {
                var imgsToLoad = swiper.imagesToLoad,
                    op = params._type === 1 ? 2 : 3,
                    idx = index * op;
                imgUrl = imgsToLoad[idx].currentSrc;
            }
            bsTotal.text(index + 1);
            return '<li class="bs-foot-pagination-li ' + className + '" style="background-image: url('+ imgUrl +')"></li>';

        },
        effect : 'coverflow',
        coverflow: {
            rotate: 30,
            stretch: 10,
            depth: 60,
            modifier: 2,
            slideShadows : false
        },
        slidesPerView: 1,
        centeredSlides: true,
        onSlideChangeStart: function(swiper){
            var idx = swiper.activeIndex;
            bsCurr.text(idx + 1);
            if(bsVcode.eq(idx).html() !== '' && bsVcode.eq(idx).children('img').css('display') === 'block') return
            appendVcode(idx)
        },
        uniqueNavElements : false,
        autoplayDisableOnInteraction: false,
        onPaginationRendered: function(swiper, paginationContainer){
            var parentPa = $('.bs-foot-pagination__wrap'),
                pagination = $(paginationContainer)
            parentPa.css('width', pagination.width() + 5 + 'px')
        },
        onInit: function (swiper) {
            /*var idx = swiper.activeIndex
            appendVcode(0)*/
        },
        onImagesReady: function(swiper) {
            //var idx = swiper.activeIndex
            appendVcode(0, function () {
                params._ldgif.hide()
            })
        },
        onTap: function(swiper){
            var _id = '#'+swiper.clickedSlide.lastElementChild.id,
                _dom = document.querySelector(_id)

            params._ldgif.show()

            function DPR() {
                if (window.devicePixelRatio && window.devicePixelRatio > 1) {
                    return window.devicePixelRatio;
                }
                return 1;
            }

            // DOM 节点计算后宽高
            var width = parseInt(_dom.clientWidth);
            var height = parseInt(_dom.clientHeight);
            // 获取像素比
            var scaleBy = DPR()*2;
            // 创建自定义 canvas 元素
            var _canvas = document.createElement('canvas');
            // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
            _canvas.width = width * scaleBy;
            _canvas.height = height * scaleBy;
            // 设定 canvas css宽高为 DOM 节点宽高
            _canvas.style.width = width + 'px';
            _canvas.style.height = height + 'px';
            // 获取画笔
            var context = _canvas.getContext('2d');

            // 将所有绘制内容放大像素比倍
            context.scale(scaleBy, scaleBy);
            context.translate(-$(_dom).offset().left, -$(_dom).offset().top);
            // imageSmoothingEnabled Canvas 2D API 用来设置图片是否平滑的属性，true表示图片平滑（默认值），false表示图片不平滑，默认的改变大小的算法会造成图片模糊并且破坏图片原有的像素。 如果那样的话，设置属性值为false。
            context.mozImageSmoothingEnabled = false;
            context.webkitImageSmoothingEnabled = false;
            context.msImageSmoothingEnabled = false;
            context.imageSmoothingEnabled = false;

            html2canvas(_dom, {
                canvas: _canvas,
                width: width,
                height: height,
                scale: scaleBy,
                dpi: window.devicePixelRatio,
                useCORS: true
            }).then(function (canvas) {
                var _src = canvas.toDataURL();
                var _cavImg = $('#cavImg');
                var _html = "<img src='"+_src+"' style='width: 100%;height: 100%;'/><aside class='closeCavImg'><i class='icon iconfont icon-guanbi'></i></aside>";
                _cavImg.html(_html).show()
                params._ldgif.hide()
                $('.closeCavImg').on('click', function () {
                    _cavImg.empty().hide()
                })
            });
        }
    })
}